
#include "server.h"

Server::Server(int port) {
	this->port = port;
}

Server::~Server() {
	if (this->isWork) {
		this->end();
	}
}

SocketServer * Server::getServerSocket() const {
	return this->serverSocket;
}

bool Server::getIsWork() const {
	return this->isWork;
}

bool Server::start() {
	this->isWork = true;
	this->serverSocket = new SocketServer();
	this->serverSocket->bindPoint(this->port);
	//client accepting loop
	while (this->isWork) {
		if (!this->serverSocket->listenConnection(5)) continue;
		SocketClient * client = this->serverSocket->acceptConnection();
		if (!client) continue;
		this->afterClientAccept(client);
		ClientServerThread * csThread = this->createClientServerThread(client);
		csThread->setServer(this);
		csThread->setClientSocket(client);
		if (csThread->Create() != wxTHREAD_NO_ERROR ) {
			delete client;
			continue;
		} else {
			csThread->Run();
			this->clientsSockets.push_back(client);
			this->threads.push_back(csThread);
		}
	}
	return true;
}

void Server::afterClientAccept(SocketClient * client) {

}

void Server::end() {
	if (this->isWork) {
		this->isWork = false;
		vector<SocketClient*>::iterator it = this->clientsSockets.begin();
		vector<SocketClient*>::iterator end = this->clientsSockets.end();
		for (; it != end; ++it) {
			delete *it;
		}
		vector<ClientServerThread*>::iterator itt = this->threads.begin();
		vector<ClientServerThread*>::iterator endt = this->threads.end();
		for (; itt != endt; ++itt) {
			if ((*itt)->Delete() != wxTHREAD_NO_ERROR) {
				printf("Can\'t delete thread");	
			}
		}
	}
}
